package br.com.almanach.jsf;

import br.com.almanach.web.Sessao;
import javax.faces.application.Application;
import javax.faces.application.ViewHandler;
import javax.faces.component.UIViewRoot;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;

public class AutenticarPhaseListener implements PhaseListener {

    public void afterPhase(PhaseEvent pe) {
    }

    public void beforePhase(PhaseEvent pe) {
        FacesContext context = FacesContext.getCurrentInstance();
        String viewId = context.getViewRoot().getViewId();
        Application app = context.getApplication();
        Sessao sessao = (Sessao) app.evaluateExpressionGet(context,"#{sessao}",Sessao.class);
        if (sessao.getUsuario() == null) {
            ViewHandler viewHandler = app.getViewHandler();
            UIViewRoot viewRoot = viewHandler.createView(context,"/seguranca/login.xhtml");
            context.setViewRoot(viewRoot);
        }
    }

    public PhaseId getPhaseId() {
        return PhaseId.RENDER_RESPONSE;
    }

}